package com.nstar.splus.model
{
	import com.nstar.base.util.StringUtils;
	import com.sina.microblog.MicroBlog;
	
	import flash.display.Graphics;
	import flash.display.NativeWindow;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.system.Capabilities;
	import flash.text.TextField;
	
	import mx.containers.Canvas;
	import mx.controls.TextArea;
	import mx.core.Window;
	import mx.core.mx_internal;
	import mx.formatters.DateFormatter;  
	use namespace mx_internal; 		
	
	/**
	 * 微博基本工具类
	 * 
	 * 
	 */ 
	public class Utils
	{
		public static const APP_ID:String = "2813055261";//我的应用ID
		public static const APP_SECRET:String = "507bc7c8347822875daff3975ec5c07f";
		private static var microBlog:MicroBlog;
		
		//取得微博应用对象
		public static function getMicroBlog():MicroBlog
		{
			if(!microBlog){
				microBlog = new MicroBlog();
				microBlog.source = APP_ID;
			}
			return microBlog;
		}
		
		public static function formatDate(d:Date, fmt:String):String
		{
			var format:DateFormatter = new DateFormatter();
			format.formatString = fmt;
			return format.format(d);
		}
		
		public static function getDateString(d:Date):String
		{
			var dateString:String;
			var now:Date = new Date();
			var interval:Number = now.getFullYear() - d.getFullYear();
			if (interval != 0)
			{
				dateString = formatDate(d, "YYYY.MM.DD HH:NN");
			}
			else
			{
				interval = now.getMonth() - d.getMonth();
				if (interval != 0)
				{
					dateString = formatDate(d, "MM月DD日 HH:NN");
				}
				else
				{
					interval = now.getDate() - d.getDate();
					if (interval != 0)
					{
						dateString = formatDate(d, "MM月DD日 HH:NN");
					}
					else
					{
						interval = now.getHours() - d.getHours();
						if (interval != 0)
						{
							dateString = formatDate(d, "今天 HH:NN");
						}
						else
						{
							interval = now.getMinutes() - d.getMinutes();
							if (interval < 0)
							{
								dateString = formatDate(d, "今天 HH:NN");
							}
							else if (interval > 0)
							{
								dateString = interval + "分钟前";
							}
							else if (interval == 0)
							{
								dateString = "1分钟前";
							}
						}
					}
				}
			}
			return dateString;
		}
		
		public static function checkInput(t:String):Boolean
		{
//			if (cnLength(t) > 280)
			if (t.length > 140)
			{
				return false;
			}
			return true;
		}
		
		public static function countInput(t:String):int
		{
			//return int( (280 - cnLength(t)) / 2 );
			return 140 - t.length;
		}
		
		public static function cnLength(str:String):int
		{
			var n:int = str.replace(/[^\x00-\xff]/g, "xx").length;
			return n;
		}
		
		public static function trimStr(str:String):String
		{
			return str.replace(/(^\s*)|(\s*$)/g, '');
		}
		
		public static function replaceSpace(str:String):String
		{
			return str.replace(/[\s*]+/g, ' ');
		}
		
		public static function transformStr(str:String):String
		{
			str = str.replace(/&quot;/g, "\"");
			str = str.replace(/&amp;/g, "&");
			str = str.replace(/>/g, "&gt;");
			str = str.replace(/</g, "&lt;");
			return str;
		}
		
		public static function getStatusHtmlText(str:String):String
		{
			str = replaceSpace(str);
			str = transformStr(str);
			var atRegx:RegExp = /@([A-Za-z0-9\u4e00-\u9fa5]+)/gi;
			var keywordRegx:RegExp = /(?<![color='])#([^#]+)#/gi;
			var shortUrlRegx:RegExp = /((http[s]?|ftp)?:\/\/(([\w-]+:)?[\w-]+@)?([\w-]+\.)+[\w-]+(:[\d]+)?(\/[\w-   .\/?%&=]*)?(#[\w,]+)?)/gi;
			str = str.replace(shortUrlRegx, "<font color='#005ED9'><a href='$1' target='_blank'>$1</a></font>");
//			str = str.replace(atRegx, "<font color='#005ED9'><a href='http://t.sina.com.cn/n/$1' target='_blank'>@$1</a></font>");
			str = str.replace(atRegx, "<font color='#005ED9'><a href='event:$1' target='_blank'>@$1</a></font>");
			str = str.replace(keywordRegx, "<font color='#005ED9'><a href='http://t.sina.com.cn/k/$1' target='_blank'>#$1#</a></font>");
			return str;
		}
		
		public static function getSourceHtmlText(str:String):String
		{
			var aRegx:RegExp = /<a[\s]+[^>]*?href[\s]?=[\s\"\']+(.*?)[\"\']+.*?>([^<]+|.*?)?<\/a>/gi;
			str = str.replace(aRegx, "$2");
			return "来自" + str;
		}
		
		public static function trunckStr(str:String, length:int):String
		{
			if ( length <= str.length )
			{
				return str;
			}
			return str.slice(0, length);
		}
		
		//返回用户超级链接
		public static function getUserLink(userID:uint,userScreenName:String):String{
			return "<b><font color='#005ED9'><a href='http://t.sina.com.cn/" + userID + "' target='_blank'>"+ userScreenName + "</a></font></b>";
			//return "<b><font color='#8080FF'><a href='event:" + userScreenName + "' target='_blank'>"+ userScreenName + "</a></font></b>";
		}
		
		//设置弹出窗口的位置
		public static function resetWindowPos(app:NativeWindow,popWin:Window):String{
			var result:String = "left";
			var relx:Number = Capabilities.screenResolutionX;
			var rely:Number = Capabilities.screenResolutionY;
			if(app.x<popWin.width){
				popWin.nativeWindow.x = app.width+app.x;
				result = "right";
			}else{
				popWin.nativeWindow.x = app.x - popWin.width;
				result = "left";
			}
			
			if((rely-app.y)<popWin.height){
				popWin.nativeWindow.y = rely - popWin.height -10;
			}else{
				popWin.nativeWindow.y = app.y + 30;
			}	
			
			return result;		
		}
		
		//使窗口居中
		public static function centerWindow(win:Window):void{
			var relx:Number = Capabilities.screenResolutionX;
			var rely:Number = Capabilities.screenResolutionY;
			win.nativeWindow.x = (relx-win.width)/2;
			win.nativeWindow.y = (rely-win.height)/2;
		}
		
		//获取消息中的@列表
		public static function getAtList(str:String):Array{
			var atRegx:RegExp = /@([A-Za-z0-9\u4e00-\u9fa5]+)/gi;
			var ary:Array = str.match(atRegx);
			//去掉重复的
			var result:Array = new Array();
			for each(var str:String in ary){
				if(result.indexOf(str)==-1){
					result.push(str);
				}
			}
			return result;
		}
		
		//获取文本输入框中当前光标相对于文本框左上角的位置
		public static function getCaretLocation(ta : TextArea) : Point {  
		    var tf : TextField = ta.getTextField() as TextField;  
		    var index : Number = tf.caretIndex;  
		    var x : Number, y : Number;  
		    var rect : Rectangle;  
		    if ('' == ta.text.charAt(index)) {  
		        if (0 == index) {  
		            // the TextArea is empty  
		            x = 2;  
		            y = 2;  
		        } else if ('\n' == ta.text.charAt(index - 1) || '\r' == ta.text.charAt(index - 1)) {  
		            // at the start of a new line, and also at the end of a the line  
		            // use lineHeight * lineIndex + yPadding as y  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * (tf.getLineIndexOfChar(index - 1) + 1) + 2;  
		        } else {  
		            // at the end of a line  
		            // use the bounds of the charater to the left of caret, and add the width of it to x  
		            rect = tf.getCharBoundaries(index - 1);  
		            x = rect.x + rect.width;  
		            y = rect.y;  
		        }  
		    } else {  
		        if ('\n' == ta.text.charAt(index) || '\r' == ta.text.charAt(index)) {  
		            // at the start of a line, but not at the end of the line  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * tf.getLineIndexOfChar(index) + 2;  
		        } else {  
		            // in middle of a line  
		            rect = tf.getCharBoundaries(index);  
		            x = rect.x;  
		            y = rect.y;  
		        }  
		    }  
		    return new Point(x, y);  
		} 
		
		//绘制消息的分隔线
		public static function drawMsgBackSperator(cav:Canvas):void{
			var g:Graphics = cav.graphics;
			g.clear();
			g.lineStyle(1,0xFFFFFF);
			g.moveTo(0,cav.height-3);
			g.lineTo(cav.width,cav.height-3);
			g.lineStyle(1,0xC2E6FF);
			g.moveTo(0,cav.height-2);
			g.lineTo(cav.width,cav.height-2);
			g.lineStyle(1,0xFFFFFF);
			g.moveTo(0,cav.height-1);
			g.lineTo(cav.width,cav.height-1);
		}
		
		//解析用户头像URL
		private static function parseProfileImageUrl(profileImageUrl:String,size:int):String{
			var result:String = StringUtils.replace(profileImageUrl,"/50/","/"+size+"/");
			return result;
		}
		
		//取30*30大小的图片
		public static function getProfileImage30(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,30);
		}

		//取50*50大小的图片
		public static function getProfileImage50(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,50);
		}

		//取180*180的头像
		public static function getProfileImage180(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,180);
		}
		
	}
}